package app.framework.front.interceptor;

import app.framework.config.FrontGlobalConfig;
import app.framework.freemarker.util.RenderUtilConfig;
import app.framework.front.util.UrlMappingUtil;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.JsonUtil;
import jasmine.framework.common.util.ResourceUtil;
import jasmine.framework.common.util.StringUtil;
import org.springframework.boot.autoconfigure.web.ServerProperties;

import java.util.Map;

/**
 * @author mh.z
 */
public class RenderUtilConfigBuilder {
    private FrontGlobalConfig frontGlobalConfig;
    private ServerProperties serverProperties;

    public FrontGlobalConfig getFrontGlobalConfig() {
        return frontGlobalConfig;
    }

    public void setFrontGlobalConfig(FrontGlobalConfig frontGlobalConfig) {
        this.frontGlobalConfig = frontGlobalConfig;
    }

    public ServerProperties getServerProperties() {
        return serverProperties;
    }

    public void setServerProperties(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    /**
     * 创建 RenderUtilConfig 对象
     *
     * @return
     */
    public RenderUtilConfig build() {
        CheckUtil.notNullProp(frontGlobalConfig, "frontGlobalConfig null");
        CheckUtil.notNullProp(serverProperties, "serverProperties null");
        RenderUtilConfig utilConfig = RenderUtilConfig.createDefault();

        // 请求上下文路径
        String contextPath = serverProperties
                .getServlet().getContextPath();
        if (StringUtil.isNotEmpty(contextPath)) {
            utilConfig.setContextPath(contextPath);
        }

        // URL 映射规则
        String urlMappingRulesConfigPath = frontGlobalConfig.getUrlMappingRulesConfigPath();
        if (StringUtil.isNotEmpty(urlMappingRulesConfigPath)) {
            Map<String, String> mappingUrlMap = UrlMappingUtil.getMappingUrlMap(urlMappingRulesConfigPath);
            utilConfig.setMappingUrls(mappingUrlMap);
        }

        String pagePlaceholdersConfigPath = frontGlobalConfig.getPagePlaceholdersConfigPath();
        if (StringUtil.isNotEmpty(pagePlaceholdersConfigPath)) {
            String json = ResourceUtil.getStringFromPath(pagePlaceholdersConfigPath);
            Map<String, Object> placeholderMap = JsonUtil.fromJson(json, Map.class);
            utilConfig.setPagePlaceholders(placeholderMap);
        }

        return utilConfig;
    }

}
